package com.cloud.custom.tasklist.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.custom.common.consts.CustomConsts;
import com.cloud.custom.tasklist.bean.TaskListSearchField;
import com.cloud.custom.tasklist.entity.TaskListField;
import com.cloud.custom.tasklist.mapper.TaskListFieldMapper;
import com.cloud.custom.tasklist.service.TaskListFieldService;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class TaskListFieldServiceImpl implements TaskListFieldService {

	@Autowired
	private TaskListFieldMapper taskListFieldMapper;

	@Override
	public List<TaskListField> listFields(long taskListId) {
		Example tlfExample = new Example(TaskListField.class);
		Example.Criteria tlfCriteria = tlfExample.createCriteria();
		tlfCriteria.andEqualTo("taskListId", taskListId);
		tlfExample.orderBy("displayOrder").asc();
		return taskListFieldMapper.selectByExample(tlfExample);
	}

	@Override
	public Long updateFields(List<TaskListField> fields) {
		long taskListId = 0;
		for (TaskListField field : fields) {
			taskListId = field.getTaskListId();
			taskListFieldMapper.updateByPrimaryKey(field);
		}
		return taskListId;
	}

	@Override
	public List<TaskListSearchField> listSearchFields(long taskListId) {
		Example example = new Example(TaskListField.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("taskListId", taskListId);
		criteria.andEqualTo("searchFlag", 1);
		example.orderBy("displayOrder");
		List<TaskListField> fields = taskListFieldMapper.selectByExample(example);
		List<TaskListSearchField> result = new ArrayList<TaskListSearchField>();
		if (null != fields && fields.size() > 0) {
			for (TaskListField field : fields) {
				TaskListSearchField searchField = new TaskListSearchField();
				searchField.setName(field.getFieldName());
				searchField.setColumnName(field.getColumnName());
				if (field.getFieldType() == CustomConsts.DATA_TYPE_DATE) {
					// 日期类型：采用日历组件
					searchField.setType(CustomConsts.SEARCH_FIELD_CALENDAR);
				} else {
					// 其他类型：采用输入框
					searchField.setType(CustomConsts.SEARCH_FIELD_INPUT);
				}
				if (!StringUtils.isEmpty(field.getSearchEnum())) {
					// 枚举类型，使用下拉框
					searchField.setType(CustomConsts.SEARCH_FIELD_DROPDOWN);
					searchField.setDictKey(field.getSearchEnum());
				}
				result.add(searchField);
			}
		}
		return result;
	}

}
